package com.example.iot.dao;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.iot.entity.po.BasePO;

import java.time.LocalDateTime;
import java.util.Collection;

/**
 * 继承重写保存更新方法，自动填充基础数据
 * @author ChenXiangpeng
 */
public class BaseDaoImpl<M extends BaseMapper<T>, T extends BasePO> extends ServiceImpl<M, T> {
    @Override
    public boolean save(T entity) {
        entity.setCreateTime(LocalDateTime.now());
        entity.setLastUpdateTime(LocalDateTime.now());
        return super.save(entity);
    }

    @Override
    public boolean updateById(T entity) {
        entity.setLastUpdateTime(LocalDateTime.now());
        return super.updateById(entity);
    }

    @Override
    public boolean update(T entity, Wrapper<T> updateWrapper) {
        entity.setLastUpdateTime(LocalDateTime.now());
        return super.update(entity, updateWrapper);
    }

    @Override
    public boolean updateBatchById(Collection<T> entityList) {
        if (CollectionUtils.isNotEmpty(entityList)){
            entityList.forEach(e->{
                e.setCreateTime(LocalDateTime.now());
                e.setLastUpdateTime(LocalDateTime.now());
            });
        }
        return super.updateBatchById(entityList);
    }

    @Override
    public boolean saveBatch(Collection<T> entityList) {
        if (CollectionUtils.isNotEmpty(entityList)){
            entityList.forEach(e->{
                e.setCreateTime(LocalDateTime.now());
                e.setLastUpdateTime(LocalDateTime.now());
            });
        }
        return super.saveBatch(entityList);
    }
}
